package chen.web.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

import org.apache.log4j.PropertyConfigurator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import chen.web.controller.forum.JSONResponse;

@Controller
public class Log4jRefreshController {

	private static final String Log4jConfigFilePath = "/log4j.properties";
	
	@RequestMapping(value="/log4j", method=RequestMethod.GET)
	public @ResponseBody JSONResponse get() throws IOException{
		AdminRoleVerify.verify();
		InputStream is = this.getClass().getResource(Log4jConfigFilePath).openStream();
		InputStreamReader reader = new InputStreamReader(is);
		StringBuilder sb = new StringBuilder();
		for(int i=reader.read(); i!=-1; i=reader.read()){
			sb.append((char)i);
		}
		reader.close();
		is.close();	
		return JSONResponse.successed(sb.toString());
	}
	
	@RequestMapping(value="/log4j", method=RequestMethod.PUT)
	public @ResponseBody JSONResponse saveAndEffect(@RequestParam String properties) throws IOException{
		AdminRoleVerify.verify();
		URL url = this.getClass().getResource(Log4jConfigFilePath);
		FileOutputStream fos = new FileOutputStream(url.getPath());
		OutputStreamWriter writer = new OutputStreamWriter(fos);
		writer.write(properties);
		writer.close();
		fos.close();
		PropertyConfigurator.configure(url);	
		return JSONResponse.successed();
	}
}
